<template>
  <div class="miniprogram-draft">
    <el-card class="draft-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>小程序草稿箱管理</span>
        </div>
      </template>

      <!-- Token配置区域 -->
      <div class="token-section">
        <el-form :model="tokenForm" label-width="180px">
          <el-form-item label="access_token">
            <el-input
              v-model="tokenForm.accessToken"
              placeholder="请输入 access_token"
              clearable
            >
              <template #prepend>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="component_verify_ticket">
            <el-input
              v-model="tokenForm.componentVerifyTicket"
              placeholder="请输入 component_verify_ticket"
              clearable
            >
              <template #prepend>
                <el-icon><Ticket /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="小程序 AppID">
            <el-input
              v-model="tokenForm.appid"
              placeholder="请输入小程序 AppID"
              clearable
              @blur="saveAppid"
            >
              <template #prepend>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="saveTokenAndGetComponentToken"
              :loading="savingToken"
              :disabled="!canUseFeatures"
            >
              保存并获取 component_access_token
            </el-button>
            <el-button
              type="warning"
              @click="openSettingsDialog"
              :disabled="!canUseFeatures"
              style="margin-left: 10px"
            >
              <el-icon><Setting /></el-icon>
              更多设置
            </el-button>
          </el-form-item>

          <!-- 显示 component_access_token -->
          <el-form-item
            label="component_access_token"
            v-if="tokenForm.componentAccessToken"
          >
            <div class="component-token-display">
              {{ tokenForm.componentAccessToken }}
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- Tab栏 -->
      <el-tabs v-model="activeTab" class="draft-tabs">
        <!-- 草稿箱列表 -->
        <el-tab-pane label="草稿箱列表" name="draft">
          <div class="tab-content">
            <el-button
              type="primary"
              @click="loadDraftList"
              :loading="loadingDrafts"
              style="margin-bottom: 16px"
            >
              <el-icon><Search /></el-icon>
              查询草稿箱
            </el-button>

            <el-table
              :data="draftList"
              v-loading="loadingDrafts"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="draft_id" label="草稿ID" width="100" />
              <el-table-column prop="user_version" label="版本号" width="120" />
              <el-table-column prop="user_desc" label="版本描述" min-width="150" />
              <el-table-column prop="source_miniprogram" label="开发小程序" width="150" />
              <el-table-column prop="source_miniprogram_appid" label="小程序AppID" width="180" />
              <el-table-column prop="developer" label="操作者" width="120" />
              <el-table-column label="创建时间" width="180">
                <template #default="scope">
                  {{ formatTimestamp(scope.row.create_time) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="small"
                    @click="addToTemplate(scope.row)"
                    :loading="addingTemplate[scope.row.draft_id]"
                  >
                    添加模版库
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-empty v-if="!loadingDrafts && draftList.length === 0" description="暂无草稿数据" />
          </div>
        </el-tab-pane>

        <!-- 模版库列表 -->
        <el-tab-pane label="模版库" name="template">
          <div class="tab-content">
            <div style="margin-bottom: 16px">
              <el-button
                type="primary"
                @click="loadTemplateList"
                :loading="loadingTemplates"
              >
                <el-icon><Search /></el-icon>
                查询模版库
              </el-button>
              <el-button
                type="danger"
                @click="handleBatchDelete"
                :disabled="selectedTemplates.length === 0"
                style="margin-left: 10px"
              >
                <el-icon><Delete /></el-icon>
                批量删除 ({{ selectedTemplates.length }})
              </el-button>
            </div>

            <el-table
              :data="templateList"
              v-loading="loadingTemplates"
              border
              stripe
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="template_id" label="模版ID" width="100" />
              <el-table-column prop="draft_id" label="草稿ID" width="100" />
              <el-table-column prop="user_version" label="版本号" width="120" />
              <el-table-column prop="user_desc" label="版本描述" min-width="150" />
              <el-table-column prop="source_miniprogram" label="开发小程序" width="150" />
              <el-table-column prop="source_miniprogram_appid" label="小程序AppID" width="180" />
              <el-table-column label="模版类型" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.template_type === 0 ? 'info' : 'success'">
                    {{ scope.row.template_type === 0 ? '普通' : '标准' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" width="180">
                <template #default="scope">
                  {{ formatTimestamp(scope.row.create_time) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleSingleDelete(scope.row)"
                    :loading="deletingTemplate[scope.row.template_id]"
                  >
                    删除
                  </el-button>
                  <el-button
                    type="success"
                    size="small"
                    @click="openUploadDialog(scope.row)"
                  >
                    上传代码
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-empty v-if="!loadingTemplates && templateList.length === 0" description="暂无模版数据" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 批量删除进度弹窗 -->
    <el-dialog
      v-model="batchDeleteDialogVisible"
      title="批量删除模版"
      width="700px"
      :close-on-click-modal="false"
      :show-close="!batchDeleting"
      @close="stopPolling"
    >
      <div class="batch-delete-content">
        <el-alert
          :title="`共选择 ${batchDeleteList.length} 个模版，已删除 ${batchDeleteSuccess} 个，失败 ${batchDeleteFail} 个`"
          type="info"
          :closable="false"
          style="margin-bottom: 16px"
        />

        <div class="delete-list">
          <div
            v-for="item in batchDeleteList"
            :key="item.template_id"
            class="delete-item"
          >
            <div class="delete-item-info">
              <span class="template-id">模版ID: {{ item.template_id }}</span>
              <span class="version">{{ item.user_version }}</span>
            </div>
            <div class="delete-item-status">
              <el-tag v-if="item.status === 'pending'" type="info">等待中</el-tag>
              <el-tag v-if="item.status === 'deleting'" type="warning">
                <el-icon class="is-loading"><Loading /></el-icon>
                删除中
              </el-tag>
              <el-tag v-if="item.status === 'success'" type="success">删除成功</el-tag>
              <el-tag v-if="item.status === 'failed'" type="danger">删除失败</el-tag>
              <span v-if="item.error" class="error-msg">{{ item.error }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDeleteDialogVisible = false" :disabled="batchDeleting">
            {{ batchDeleting ? '删除中...' : '关闭' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传代码弹窗 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传小程序代码"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="140px">
        <el-form-item label="模版ID">
          <el-input v-model="uploadForm.templateId" disabled />
        </el-form-item>

        <el-form-item label="目标小程序AppID" prop="appid" required>
          <el-input
            v-model="uploadForm.appid"
            placeholder="请输入目标小程序的AppID"
            clearable
          />
        </el-form-item>

        <el-form-item label="版本号" prop="userVersion" required>
          <el-input
            v-model="uploadForm.userVersion"
            placeholder="请输入版本号"
            clearable
          />
        </el-form-item>

        <el-form-item label="版本描述" prop="userDesc" required>
          <el-input
            v-model="uploadForm.userDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入版本描述"
            clearable
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploading">
            提交上传
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更多设置弹窗 -->
    <el-dialog
      v-model="settingsDialogVisible"
      title="更多设置"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="settingsTab">
        <el-tab-pane label="初次部署小程序" name="init">
          <el-form
            :model="initDeployForm"
            :rules="initDeployRules"
            ref="initDeployFormRef"
            label-width="180px"
            style="padding: 20px 0"
          >
            <el-form-item label="服务器域名" prop="serverDomain" required>
              <el-input
                v-model="initDeployForm.serverDomain"
                placeholder="例如: www.qq.com (不需要http://等协议)"
                clearable
              />
              <div class="form-tip">不需要带http://等协议内容，严格按照 www.qq.com 的写法</div>
            </el-form-item>

            <el-form-item label="设置订单页面path" prop="setOrderPath">
              <el-radio-group v-model="initDeployForm.setOrderPath">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="订单页面路径"
              prop="orderPath"
              v-if="initDeployForm.setOrderPath"
              required
            >
              <el-input
                v-model="initDeployForm.orderPath"
                placeholder="pages/order/order"
                clearable
              />
              <div class="form-tip">小程序订单页面的路径</div>
            </el-form-item>
          </el-form>

          <div v-if="deployProgress.length > 0" class="deploy-progress">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in deployProgress"
                :key="index"
                :type="item.status"
                :icon="item.icon"
                :timestamp="item.timestamp"
              >
                {{ item.message }}
                <div v-if="item.detail" class="progress-detail">{{ item.detail }}</div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settingsDialogVisible = false" :disabled="deploying">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="handleInitDeploy"
            :loading="deploying"
            :disabled="deploying"
          >
            {{ deploying ? '部署中...' : '确认' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onUnmounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatTimestamp } from '../utils/format.js';
import { WECHAT_CONFIG, STORAGE_KEYS } from '../utils/constants.js';

export default {
  name: 'MiniprogramDraft',
  setup() {
    // Token相关
    const tokenForm = reactive({
      accessToken: '',
      componentVerifyTicket: '',
      componentAccessToken: '',
      appid: ''
    });
    const savingToken = ref(false);

    // 计算是否可以使用功能(基于token两个输入框配置)
    const canUseFeatures = computed(() => {
      return tokenForm.accessToken && tokenForm.componentVerifyTicket;
    });

    // Tab切换
    const activeTab = ref('draft');

    // 草稿箱列表
    const draftList = ref([]);
    const loadingDrafts = ref(false);
    const addingTemplate = ref({});

    // 模版库列表
    const templateList = ref([]);
    const loadingTemplates = ref(false);
    const selectedTemplates = ref([]);
    const deletingTemplate = ref({});

    // 批量删除相关
    const batchDeleteDialogVisible = ref(false);
    const batchDeleteList = ref([]);
    const batchDeleting = ref(false);
    const batchDeleteSuccess = ref(0);
    const batchDeleteFail = ref(0);
    const currentTaskId = ref(null);
    const pollTimer = ref(null);

    // 上传代码弹窗
    const uploadDialogVisible = ref(false);
    const uploadForm = reactive({
      templateId: '',
      appid: '',
      userVersion: '',
      userDesc: ''
    });
    const uploadFormRef = ref(null);
    const uploading = ref(false);

    // 表单验证规则
    const uploadRules = {
      appid: [{ required: true, message: '请输入目标小程序AppID', trigger: 'blur' }],
      userVersion: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
      userDesc: [{ required: true, message: '请输入版本描述', trigger: 'blur' }]
    };

    // 更多设置弹窗
    const settingsDialogVisible = ref(false);
    const settingsTab = ref('init');
    const deploying = ref(false);
    const deployProgress = ref([]);

    // 初次部署表单
    const initDeployForm = reactive({
      serverDomain: '',
      setOrderPath: true,
      orderPath: 'pages/order/order'
    });
    const initDeployFormRef = ref(null);

    // 初次部署表单验证规则
    const initDeployRules = {
      serverDomain: [
        { required: true, message: '请输入服务器域名', trigger: 'blur' }
      ],
      orderPath: [
        { required: true, message: '请输入订单页面路径', trigger: 'blur' }
      ]
    };

    // 从本地存储加载token
    const loadTokensFromStorage = () => {
      const savedAccessToken = localStorage.getItem(STORAGE_KEYS.WX_ACCESS_TOKEN);
      const savedComponentVerifyTicket = localStorage.getItem(STORAGE_KEYS.WX_COMPONENT_VERIFY_TICKET);
      const savedComponentAccessToken = localStorage.getItem(STORAGE_KEYS.WX_COMPONENT_ACCESS_TOKEN);
      const savedAppid = localStorage.getItem(STORAGE_KEYS.WX_APPID);

      if (savedAccessToken) tokenForm.accessToken = savedAccessToken;
      if (savedComponentVerifyTicket) tokenForm.componentVerifyTicket = savedComponentVerifyTicket;
      if (savedComponentAccessToken) tokenForm.componentAccessToken = savedComponentAccessToken;
      if (savedAppid) tokenForm.appid = savedAppid;
    };

    // 保存appid到本地存储
    const saveAppid = () => {
      if (tokenForm.appid) {
        localStorage.setItem(STORAGE_KEYS.WX_APPID, tokenForm.appid);
      }
    };

    // 保存token并获取component_access_token
    const saveTokenAndGetComponentToken = async () => {
      if (!tokenForm.componentVerifyTicket) {
        ElMessage.warning('请输入 component_verify_ticket');
        return;
      }

      savingToken.value = true;
      try {
        const response = await axios.post('/api/miniprogram/component-token', {
          component_appid: WECHAT_CONFIG.COMPONENT_APPID,
          component_appsecret: WECHAT_CONFIG.COMPONENT_APPSECRET,
          component_verify_ticket: tokenForm.componentVerifyTicket
        });

        if (response.data.component_access_token) {
          tokenForm.componentAccessToken = response.data.component_access_token;

          // 保存到本地存储
          localStorage.setItem(STORAGE_KEYS.WX_ACCESS_TOKEN, tokenForm.accessToken);
          localStorage.setItem(STORAGE_KEYS.WX_COMPONENT_VERIFY_TICKET, tokenForm.componentVerifyTicket);
          localStorage.setItem(STORAGE_KEYS.WX_COMPONENT_ACCESS_TOKEN, tokenForm.componentAccessToken);

          ElMessage.success('获取 component_access_token 成功');
        } else {
          ElMessage.error('获取 component_access_token 失败: ' + (response.data.errmsg || '未知错误'));
        }
      } catch (error) {
        console.error('获取 component_access_token 失败:', error);
        ElMessage.error('获取 component_access_token 失败: ' + (error.response?.data?.errmsg || error.message));
      } finally {
        savingToken.value = false;
      }
    };

    // 加载草稿箱列表
    const loadDraftList = async () => {
      if (!tokenForm.componentAccessToken) {
        ElMessage.warning('请先获取 component_access_token');
        return;
      }

      loadingDrafts.value = true;
      try {
        const response = await axios.get('/api/miniprogram/draft-list', {
          params: {
            access_token: tokenForm.componentAccessToken
          }
        });

        if (response.data.errcode === 0 || response.data.draft_list) {
          // 按创建时间倒序排列(最新的在最上面)
          const list = response.data.draft_list || [];
          draftList.value = list.sort((a, b) => b.create_time - a.create_time);
          ElMessage.success(`成功加载 ${draftList.value.length} 条草稿数据`);
        } else {
          ElMessage.error('加载草稿箱失败: ' + (response.data.errmsg || '未知错误'));
        }
      } catch (error) {
        console.error('加载草稿箱失败:', error);
        ElMessage.error('加载草稿箱失败: ' + (error.response?.data?.errmsg || error.message));
      } finally {
        loadingDrafts.value = false;
      }
    };

    // 添加到模版库
    const addToTemplate = async (draft) => {
      if (!tokenForm.componentAccessToken) {
        ElMessage.warning('请先获取 component_access_token');
        return;
      }

      addingTemplate.value[draft.draft_id] = true;
      try {
        const response = await axios.post('/api/miniprogram/add-to-template', {
          access_token: tokenForm.componentAccessToken,
          draft_id: draft.draft_id,
          template_type: 0
        });

        if (response.data.errcode === 0) {
          ElMessage.success('添加到模版库成功');
          // 自动刷新模版库列表
          if (activeTab.value === 'template') {
            await loadTemplateList();
          }
        } else {
          ElMessage.error('添加到模版库失败: ' + (response.data.errmsg || '未知错误'));
        }
      } catch (error) {
        console.error('添加到模版库失败:', error);
        ElMessage.error('添加到模版库失败: ' + (error.response?.data?.errmsg || error.message));
      } finally {
        delete addingTemplate.value[draft.draft_id];
      }
    };

    // 加载模版库列表
    const loadTemplateList = async () => {
      if (!tokenForm.componentAccessToken) {
        ElMessage.warning('请先获取 component_access_token');
        return;
      }

      loadingTemplates.value = true;
      try {
        const response = await axios.get('/api/miniprogram/template-list', {
          params: {
            access_token: tokenForm.componentAccessToken,
            template_type: 0
          }
        });

        if (response.data.errcode === 0 || response.data.template_list) {
          // 按创建时间倒序排列(最新的在最上面)
          const list = response.data.template_list || [];
          templateList.value = list.sort((a, b) => b.create_time - a.create_time);
          ElMessage.success(`成功加载 ${templateList.value.length} 条模版数据`);
        } else {
          ElMessage.error('加载模版库失败: ' + (response.data.errmsg || '未知错误'));
        }
      } catch (error) {
        console.error('加载模版库失败:', error);
        ElMessage.error('加载模版库失败: ' + (error.response?.data?.errmsg || error.message));
      } finally {
        loadingTemplates.value = false;
      }
    };

    // 打开上传代码弹窗
    const openUploadDialog = (template) => {
      uploadForm.templateId = template.template_id;
      uploadForm.userVersion = template.user_version;
      uploadForm.userDesc = template.user_desc;
      uploadForm.appid = '';
      uploadDialogVisible.value = true;
    };

    // 提交上传代码
    const submitUpload = async () => {
      if (!uploadFormRef.value) return;

      await uploadFormRef.value.validate(async (valid) => {
        if (!valid) return;

        if (!tokenForm.accessToken) {
          ElMessage.warning('请先输入 access_token');
          return;
        }

        uploading.value = true;
        try {
          const response = await axios.post('/api/miniprogram/commit-code', {
            access_token: tokenForm.accessToken,
            template_id: uploadForm.templateId,
            ext_json: '{}',
            user_version: uploadForm.userVersion,
            user_desc: uploadForm.userDesc
          });

          if (response.data.errcode === 0) {
            ElMessage.success('代码上传成功');
            uploadDialogVisible.value = false;
          } else {
            ElMessage.error('代码上传失败: ' + (response.data.errmsg || '未知错误'));
          }
        } catch (error) {
          console.error('代码上传失败:', error);
          ElMessage.error('代码上传失败: ' + (error.response?.data?.errmsg || error.message));
        } finally {
          uploading.value = false;
        }
      });
    };

    // 表格选择变化
    const handleSelectionChange = (selection) => {
      selectedTemplates.value = selection;
    };

    // 单个删除模版
    const handleSingleDelete = async (template) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除模版 ${template.template_id} (${template.user_version}) 吗?`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        if (!tokenForm.componentAccessToken) {
          ElMessage.warning('请先获取 component_access_token');
          return;
        }

        deletingTemplate.value[template.template_id] = true;
        try {
          const response = await axios.post('/api/miniprogram/delete-template', {
            access_token: tokenForm.componentAccessToken,
            template_id: template.template_id
          });

          if (response.data.errcode === 0) {
            ElMessage.success('删除模版成功');
            // 刷新模版库列表
            await loadTemplateList();
          } else {
            ElMessage.error('删除模版失败: ' + (response.data.errmsg || '未知错误'));
          }
        } catch (error) {
          console.error('删除模版失败:', error);
          ElMessage.error('删除模版失败: ' + (error.response?.data?.errmsg || error.message));
        } finally {
          delete deletingTemplate.value[template.template_id];
        }
      } catch {
        // 用户取消删除
      }
    };

    // 轮询获取删除任务状态
    const pollDeleteTaskStatus = async (taskId) => {
      try {
        const response = await axios.get(`/api/miniprogram/delete-task/${taskId}`);

        if (response.data.success && response.data.task) {
          const task = response.data.task;

          // 更新批量删除列表
          batchDeleteList.value = task.templates;
          batchDeleteSuccess.value = task.progress.success;
          batchDeleteFail.value = task.progress.failed;

          // 如果任务完成,停止轮询
          if (task.status === 'completed') {
            if (pollTimer.value) {
              clearInterval(pollTimer.value);
              pollTimer.value = null;
            }

            batchDeleting.value = false;

            // 刷新模版库列表
            await loadTemplateList();

            ElMessage.success(
              `批量删除完成: 成功 ${batchDeleteSuccess.value} 个，失败 ${batchDeleteFail.value} 个`
            );
          }
        }
      } catch (error) {
        console.error('获取删除任务状态失败:', error);

        // 如果轮询失败,停止轮询
        if (pollTimer.value) {
          clearInterval(pollTimer.value);
          pollTimer.value = null;
        }
        batchDeleting.value = false;
        ElMessage.error('获取删除进度失败: ' + error.message);
      }
    };

    // 批量删除模版
    const handleBatchDelete = async () => {
      if (selectedTemplates.value.length === 0) {
        ElMessage.warning('请先选择要删除的模版');
        return;
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedTemplates.value.length} 个模版吗?`,
          '确认批量删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        if (!tokenForm.componentAccessToken) {
          ElMessage.warning('请先获取 component_access_token');
          return;
        }

        // 初始化批量删除列表
        batchDeleteList.value = selectedTemplates.value.map(item => ({
          ...item,
          status: 'pending',
          error: null
        }));
        batchDeleteSuccess.value = 0;
        batchDeleteFail.value = 0;
        batchDeleteDialogVisible.value = true;
        batchDeleting.value = true;

        // 创建批量删除任务
        const response = await axios.post('/api/miniprogram/batch-delete-templates', {
          access_token: tokenForm.componentAccessToken,
          templates: selectedTemplates.value
        });

        if (response.data.success) {
          currentTaskId.value = response.data.taskId;
          ElMessage.success('已创建删除任务,正在后台处理...');

          // 开始轮询任务状态(每1秒查询一次)
          pollTimer.value = setInterval(() => {
            pollDeleteTaskStatus(currentTaskId.value);
          }, 1000);

          // 立即查询一次
          pollDeleteTaskStatus(currentTaskId.value);
        } else {
          batchDeleting.value = false;
          ElMessage.error('创建删除任务失败: ' + response.data.error);
        }
      } catch (error) {
        batchDeleting.value = false;
        ElMessage.error('批量删除失败: ' + error.message);
      }
    };

    // 停止轮询
    const stopPolling = () => {
      if (pollTimer.value) {
        clearInterval(pollTimer.value);
        pollTimer.value = null;
      }
    };

    // 打开更多设置弹窗
    const openSettingsDialog = () => {
      settingsDialogVisible.value = true;
      deployProgress.value = [];
    };

    // 添加部署进度
    const addDeployProgress = (message, status = 'primary', detail = '') => {
      deployProgress.value.push({
        message,
        status,
        detail,
        timestamp: new Date().toLocaleTimeString(),
        icon: status === 'success' ? 'Check' : status === 'danger' ? 'Close' : 'Loading'
      });
    };

    // 处理初次部署
    const handleInitDeploy = async () => {
      if (!initDeployFormRef.value) return;

      await initDeployFormRef.value.validate(async (valid) => {
        if (!valid) return;

        deploying.value = true;
        deployProgress.value = [];

        try {
          // 步骤1: 设置第三方服务平台服务器域名
          await setupServerDomain();

          // 步骤2: 设置小程序服务器域名
          await setupMiniprogramDomain();

          // 步骤3: 设置订单页面path (如果需要)
          if (initDeployForm.setOrderPath) {
            await setupOrderPath();
          }

          // 步骤4: 设置隐私保护指引
          await setupPrivacySetting();

          addDeployProgress('✅ 初次部署完成！', 'success');
          ElMessage.success('初次部署成功！');
        } catch (error) {
          addDeployProgress(`❌ 部署失败: ${error.message}`, 'danger');
          ElMessage.error('部署失败: ' + error.message);
        } finally {
          deploying.value = false;
        }
      });
    };

    // 步骤1: 设置第三方服务平台服务器域名
    const setupServerDomain = async () => {
      addDeployProgress('正在检查第三方服务平台域名...', 'primary');

      // 先获取当前域名配置
      const getResponse = await axios.post(
        `/api/miniprogram/modify-server-domain`,
        {
          access_token: tokenForm.componentAccessToken,
          action: 'get'
        }
      );

      if (getResponse.data.errcode !== 0) {
        throw new Error(`获取服务平台域名失败: ${getResponse.data.errmsg}`);
      }

      addDeployProgress('已获取当前服务平台域名配置', 'success');

      // 检查域名是否已存在
      const testingDomains = getResponse.data.testing_wxa_server_domain || '';
      const domainList = testingDomains.split(';').filter(d => d);
      const domainExists = domainList.includes(initDeployForm.serverDomain);

      if (domainExists) {
        addDeployProgress('服务平台域名已存在，跳过添加', 'success');
        return;
      }

      // 添加域名
      addDeployProgress(`正在添加服务平台域名: ${initDeployForm.serverDomain}`, 'primary');

      const addResponse = await axios.post(
        `/api/miniprogram/modify-server-domain`,
        {
          access_token: tokenForm.componentAccessToken,
          action: 'add',
          is_modify_published_together: true,
          wxa_server_domain: initDeployForm.serverDomain
        }
      );

      if (addResponse.data.errcode !== 0) {
        throw new Error(`添加服务平台域名失败: ${addResponse.data.errmsg}`);
      }

      addDeployProgress('✅ 服务平台域名设置成功', 'success');
    };

    // 步骤2: 设置小程序服务器域名
    const setupMiniprogramDomain = async () => {
      addDeployProgress('正在检查小程序服务器域名...', 'primary');

      // 先获取当前域名配置
      const getResponse = await axios.post(
        `/api/miniprogram/modify-miniprogram-domain`,
        {
          access_token: tokenForm.accessToken,
          action: 'get'
        }
      );

      if (getResponse.data.errcode !== 0) {
        throw new Error(`获取小程序域名失败: ${getResponse.data.errmsg}`);
      }

      addDeployProgress('已获取当前小程序域名配置', 'success');

      // 检查域名是否已存在(模糊匹配)
      const requestdomains = getResponse.data.requestdomain || [];
      const domainExists = requestdomains.some(domain => domain.includes(initDeployForm.serverDomain));

      if (domainExists) {
        addDeployProgress('小程序域名已存在，跳过添加', 'success');
        return;
      }

      // 添加域名
      addDeployProgress(`正在添加小程序域名: ${initDeployForm.serverDomain}`, 'primary');

      const serverDomain = initDeployForm.serverDomain;
      const addResponse = await axios.post(
        `/api/miniprogram/modify-miniprogram-domain`,
        {
          access_token: tokenForm.accessToken,
          action: 'add',
          requestdomain: [`https://${serverDomain}`],
          wsrequestdomain: [`wss://${serverDomain}`],
          uploaddomain: [`https://${serverDomain}`],
          downloaddomain: [`https://${serverDomain}`],
          udpdomain: [`udp://${serverDomain}`],
          tcpdomain: [`tcp://${serverDomain}`]
        }
      );

      if (addResponse.data.errcode !== 0) {
        throw new Error(`添加小程序域名失败: ${addResponse.data.errmsg}`);
      }

      addDeployProgress('✅ 小程序域名设置成功', 'success');
    };

    // 步骤3: 设置订单页面path
    const setupOrderPath = async () => {
      addDeployProgress(`正在设置订单页面路径: ${initDeployForm.orderPath}`, 'primary');

      const response = await axios.post(
        `/api/miniprogram/add-to-template-path`,
        {
          access_token: tokenForm.componentAccessToken,
          batch_req: {
            path: initDeployForm.orderPath,
            appid_list: [tokenForm.appid]
          }
        }
      );

      if (response.data.errcode !== 0) {
        throw new Error(`设置订单页面路径失败: ${response.data.errmsg}`);
      }

      addDeployProgress('✅ 订单页面路径设置成功', 'success');
    };

    // 步骤4: 设置隐私保护指引
    const setupPrivacySetting = async () => {
      addDeployProgress('正在设置隐私保护指引...', 'primary');

      const response = await axios.post(
        `/api/miniprogram/set-privacy-setting`,
        {
          access_token: tokenForm.accessToken,
          privacy_ver: 2,
          setting_list: [
            { privacy_key: 'UserInfo', privacy_text: '展示用户身份' },
            { privacy_key: 'Album', privacy_text: '照片上传' },
            { privacy_key: 'Camera', privacy_text: '拍照上传评价' },
            { privacy_key: 'PhoneNumber', privacy_text: '登录使用' },
            { privacy_key: 'EXIDNumber', privacy_text: '用户身份认证（选填）' },
            { privacy_key: 'MessageFile', privacy_text: '选择照片上传' },
            { privacy_key: 'PhoneNumber', privacy_text: '手机号' },
            { privacy_key: 'Clipboard', privacy_text: '剪切板复制订单号' }
          ],
          owner_setting: {
            contact_phone: '025-85303775',
            notice_method: '电话'
          }
        }
      );

      if (response.data.errcode !== 0) {
        throw new Error(`设置隐私保护指引失败: ${response.data.errmsg}`);
      }

      addDeployProgress('✅ 隐私保护指引设置成功', 'success');
    };

    // 初始化：加载本地存储的token
    loadTokensFromStorage();

    // 组件卸载时清理定时器
    onUnmounted(() => {
      stopPolling();
    });

    return {
      tokenForm,
      savingToken,
      canUseFeatures,
      activeTab,
      draftList,
      loadingDrafts,
      addingTemplate,
      templateList,
      loadingTemplates,
      selectedTemplates,
      deletingTemplate,
      batchDeleteDialogVisible,
      batchDeleteList,
      batchDeleting,
      batchDeleteSuccess,
      batchDeleteFail,
      currentTaskId,
      pollTimer,
      uploadDialogVisible,
      uploadForm,
      uploadFormRef,
      uploadRules,
      uploading,
      settingsDialogVisible,
      settingsTab,
      deploying,
      deployProgress,
      initDeployForm,
      initDeployFormRef,
      initDeployRules,
      saveAppid,
      saveTokenAndGetComponentToken,
      loadDraftList,
      addToTemplate,
      loadTemplateList,
      handleSelectionChange,
      handleSingleDelete,
      handleBatchDelete,
      pollDeleteTaskStatus,
      stopPolling,
      openUploadDialog,
      submitUpload,
      openSettingsDialog,
      handleInitDeploy,
      formatTimestamp
    };
  }
};
</script>

<style scoped>
.miniprogram-draft {
  padding: 20px;
}

.draft-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: none;
  border-radius: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #2c3e50;
}

.token-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.component-token-display {
  padding: 8px 12px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  word-break: break-all;
  line-height: 1.5;
}

.draft-tabs {
  margin-top: 24px;
}

.tab-content {
  padding: 16px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.batch-delete-content {
  max-height: 500px;
  overflow-y: auto;
}

.delete-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.delete-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fafafa;
}

.delete-item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.template-id {
  font-weight: bold;
  color: #303133;
}

.version {
  font-size: 12px;
  color: #909399;
}

.delete-item-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-msg {
  font-size: 12px;
  color: #f56c6c;
  margin-left: 8px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.deploy-progress {
  margin-top: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  max-height: 400px;
  overflow-y: auto;
}

.progress-detail {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* Loading 动画样式已移除 - 使用Element Plus默认样式 */
</style>
